<?php

namespace app\api\model;

use think\Model;
use think\Request;
use think\Db;
use app\api\model\Client;

class Log extends Model
{
    public function visitor_list()
    {
        $count = 10;
        $page = !empty(input("post.curr")) ? input("post.curr") : 1;
        $logmin = !empty(input("post.logmin")) ? strtotime(input("post.logmin")) : 0;
        $logmax = !empty(input("post.logmax")) ? strtotime(input("post.logmax") . " 23:59:59") : time();
        $where['time'] = ['between', [$logmin, $logmax]];
        if (!empty(input("post.content"))) {
            $where['ip|OS|all_url|browser'] = ["like", input("post.content")];
        }
        $info_count = Db::connect("db_mongo")->name("visitor_log")->where($where)->count();
        $pages = ceil($info_count / $count);
        $info = Db::connect("db_mongo")->name("visitor_log")->where($where)->order('time', 'desc')->page($page, $count)->select();
        $result['pages'] = $pages;
        $result['info'] = $info;
        return $result;
    }

    public function add_visitor()
    {
        $info = self::visitor_info();
        $add = Db::connect("db_mongo")->name("VisitorLog")->insert($info);
        if ($add) {
            return "success";
        } else {
            return "error";
        }
    }

    private function visitor_info()
    {
        $info['all_url'] = Request::instance()->url(true);
        $info['url'] = Request::instance()->baseurl(true);
        $info['time'] = time();
        $Client = new Client;
        $info['browser'] = $Client->get_browser();
        $info['lang'] = $Client->get_lang();
        $info['OS'] = $Client->get_os();
        $form = $Client->get_ip_from();
        $info['ip'] = $form['ip'];
        $info['country'] = $form['country'];
        $info['region'] = $form['region'];
        $info['city'] = $form['city'];
        $info['county'] = $form['county'];
        $info['area'] = $form['area'];
        $info['isp'] = $form['isp'];
        return $info;
    }
}